package com.app.business.service.newTextForCs;

import com.app.business.model.newTextForCs.TextContract;
import com.app.business.model.newTextForCs.TextHistory;
import com.app.business.model.newTextForCs.TextHouseHoldAndArea;
import com.app.business.model.newTextForCs.TextParameter;
import com.app.system.jpa.JpaBaseDao;
import com.app.system.jpa.PageBean;
import com.app.system.jpa.Wrapper;
import com.app.system.utils.CollectionUtils;
import com.app.system.utils.dataType.BigDecimalUtils;
import com.app.system.utils.exception.Precondition;
import com.google.common.collect.Maps;
import org.hibernate.transform.Transformers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.persistence.Query;
import javax.transaction.Transactional;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

/**
 * 测算记录保存管理
 * Created by ddz on 2020/1/20.
 */
@SuppressWarnings(value = "ALL")
@Service
@Transactional
public class TextHistoryService extends JpaBaseDao<TextHistory, Integer> {

    @Autowired
    private TextHouseHoldAndAreaService textHouseHoldAndAreaService;
    @Autowired
    private TextContractService textContractService;


    /**
     * 分页处理
     *
     * @return
     */
    public PageBean<TextHistory> getTextHistoryPageBean() {
        //查询语句
        StringBuffer query = new StringBuffer("h from TextHistory h inner join fetch h.textContract c inner join fetch h.textParameter p");
        PageBean pageBean = new PageBean();
        pageBean.setPageSize(Integer.MAX_VALUE);
        StringBuffer orderBy = new StringBuffer("c.projectCode,c.chooseNum");
        Wrapper wrapper = new Wrapper(pageBean, query, null, orderBy);
        //默认排序(PageBean指定排序字段类型的话，则默认排序不使用)
        wrapper.initSearchParams();

        return this.pageHql(wrapper);
    }

    /**
     * 删除某参数配置下所有的面积户型配置数据
     *
     * @param
     */
    public synchronized void deleteTextHistoryByTextParameterIdAndTextContractId(Integer textParameterId, Integer textContractId) {
        String sql = "delete from text_history where text_parameter_id = :textParameterId AND text_contract_id=:textContractId";
        this.entityManager.createNativeQuery(sql).setParameter("textParameterId", textParameterId).setParameter("textContractId", textContractId).executeUpdate();
    }

    /**
     * 参数配置数据保存
     */
    public void dataFormSave(TextParameter textParameter, String projectCode) {
        Precondition.checkAjaxArguement(textParameter != null, "1111", "未找到相关配置，保存失败！");
        Precondition.checkAjaxArguement(projectCode != null && !projectCode.equals(""), "1111", "未找到相关配置，保存失败！");

        //得到户型面积配置
        List<TextHouseHoldAndArea> textHouseHoldAndAreaList = this.textHouseHoldAndAreaService.getTextHouseHoldAndAreaListByTextParameterId(textParameter.getId());
        //得到项目批次编号的协议
        List<TextContract> textContractList = this.textContractService.getTextContractListByProjectCode(projectCode);

        for (TextContract textContract : textContractList) {
            BigDecimal kazArea = textContract.getKazArea();
            TextHistory textHistory = new TextHistory();
            Integer count = null;
            for (TextHouseHoldAndArea textHouseHoldAndArea : textHouseHoldAndAreaList) {
                BigDecimal area = textHouseHoldAndArea.getArea();//面积区间
                BigDecimal minArea = textHouseHoldAndArea.getMinArea();//最小可选面积
                Integer sortNum = textHouseHoldAndArea.getSortNum();//排序号

                //可安置面积大于最小可选面积才可以选房
                if (kazArea.compareTo(minArea) >= 0) {
                    BigDecimal[] results = kazArea.divideAndRemainder(area);
                    BigDecimal result0 = results[0];//商
                    BigDecimal result1 = results[1];//余
                    if (sortNum != null && sortNum == 10) {
                        count = 0;
                        if (result1.compareTo(minArea) >= 0) {
                            count = result0.intValue() + 1;
                        } else {
                            count = result0.intValue();
                        }
                        textHistory.setCount1(count);
                        textHistory.setName1(textHouseHoldAndArea.getHouseHold() + area.toString());
                        kazArea = BigDecimalUtils.getBigAndBigSub(kazArea, BigDecimalUtils.getBigAndIntMul(area, count));
                    }

                    if (sortNum != null && sortNum == 20) {
                        count = 0;
                        if (result1.compareTo(minArea) >= 0) {
                            count = result0.intValue() + 1;
                        } else {
                            count = result0.intValue();
                        }
                        textHistory.setCount2(count);
                        textHistory.setName2(textHouseHoldAndArea.getHouseHold() + area.toString());
                        kazArea = BigDecimalUtils.getBigAndBigSub(kazArea, BigDecimalUtils.getBigAndIntMul(area, count));
                    }

                    if (sortNum != null && sortNum == 30) {
                        count = 0;
                        if (result1.compareTo(minArea) >= 0) {
                            count = result0.intValue() + 1;
                        } else {
                            count = result0.intValue();
                        }
                        textHistory.setCount3(count);
                        textHistory.setName3(textHouseHoldAndArea.getHouseHold() + area.toString());
                        kazArea = BigDecimalUtils.getBigAndBigSub(kazArea, BigDecimalUtils.getBigAndIntMul(area, count));
                    }

                    if (sortNum != null && sortNum == 40) {
                        count = 0;
                        if (result1.compareTo(minArea) >= 0) {
                            count = result0.intValue() + 1;
                        } else {
                            count = result0.intValue();
                        }
                        textHistory.setCount4(count);
                        textHistory.setName4(textHouseHoldAndArea.getHouseHold() + area.toString());
                        kazArea = BigDecimalUtils.getBigAndBigSub(kazArea, BigDecimalUtils.getBigAndIntMul(area, count));

                    }

                    if (sortNum != null && sortNum == 50) {
                        count = 0;
                        if (result1.compareTo(minArea) >= 0) {
                            count = result0.intValue() + 1;
                        } else {
                            count = result0.intValue();
                        }
                        textHistory.setCount5(count);
                        textHistory.setName5(textHouseHoldAndArea.getHouseHold() + area.toString());
                        kazArea = BigDecimalUtils.getBigAndBigSub(kazArea, BigDecimalUtils.getBigAndIntMul(area, count));
                    }
                }
            }
            textHistory.setSyArea(kazArea);
            textHistory.setTextContract(textContract);
            textHistory.setTextParameter(textParameter);
            this.deleteTextHistoryByTextParameterIdAndTextContractId(textParameter.getId(), textContract.getId());
            this.save(textHistory);
        }
    }


    /**
     * 测算情况汇总表
     * 根据批次编号得到该编号下项目数量情况
     *
     * @return
     */
    public Map<String, Map> getCountStatisticsByAzProjectCode(String projectCode, Integer textParameterId) {

        StringBuffer sql = new StringBuffer("SELECT c.project_name AS projectName,COUNT(c.id) AS chooseNumCount, ");
        sql.append(" SUM(c.kaz_area) AS kazAreaNum,");
        sql.append(" SUM(th.count1) AS count1Num,");
        sql.append(" SUM(th.count2) AS count2Num,");
        sql.append(" SUM(th.count3) AS count3Num,");
        sql.append(" SUM(th.count4) AS count4Num,");
        sql.append(" SUM(th.count5) AS count5Num, ");
        sql.append(" SUM(CASE WHEN th.sy_area > 0 THEN IFNULL(th.sy_area,0) ELSE 0 END) AS moreArea, ");
        sql.append(" SUM(CASE WHEN th.sy_area < 0 THEN IFNULL(th.sy_area,0) ELSE 0 END) AS lessArea  ");
        sql.append(" FROM text_history th INNER JOIN  text_contract c ON th.text_contract_id=c.id ");
        sql.append(" WHERE c.project_code=:projectCode  and th.text_parameter_id =:textParameterId ");
        sql.append(" GROUP BY projectName");

        Query query = this.entityManager.createNativeQuery(sql.toString()).setParameter("projectCode", projectCode).setParameter("textParameterId", textParameterId);
        List<Map> mapList = query.unwrap(org.hibernate.SQLQuery.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP).list();
        Map<String, Map> countMap = Maps.newHashMap();
        if (CollectionUtils.isNotEmpty(mapList)) {
            for (Map map : mapList) {
                String projectName = map.get("projectName").toString();
                countMap.put(projectName, map);
            }
        }
        return countMap;
    }
}
